<%--
  Created by IntelliJ IDEA.
  User: 30919
  Date: 2025/9/17
  Time: 10:55
  To change this template use File | Settings | File Templates.
--%>
<%--
  Created by IntelliJ IDEA.
  User: 30919
  Date: 2025/8/26
  Time: 18:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>
<!-- SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
    :root {
        --bs-primary: #3b7ddd;
        --bs-primary-rgb: 59, 125, 221;
        --bs-success: #1cbb8c;
        --bs-success-rgb: 28, 187, 140;
        --bs-danger: #fc5b69;
        --bs-danger-rgb: 252, 91, 105;
        --bs-warning: #f7b84b;
        --bs-warning-rgb: 247, 184, 75;
        --bs-light-bg: #f5f7fa;
    }

    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border: none;
        margin-bottom: 1.5rem;
    }

    .card-header {
        background-color: #fff;
        border-bottom: 1px solid #eaeef1;
        padding: 1rem 1.25rem;
        font-weight: 600;
        color: #2c3e50;
    }

    .table-container {
        background-color: #fff;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .table th {
        background-color: var(--bs-light-bg);
        color: #2c3e50;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-top: none;
    }

    .table td {
        padding: 0.75rem 1rem;
        vertical-align: middle;
    }

    .status-badge {
        padding: 0.35em 0.65em;
        border-radius: 0.25rem;
        font-size: 0.75em;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .bg-enabled {
        background-color: rgba(var(--bs-success-rgb), 0.15);
        color: var(--bs-success);
    }

    .bg-disabled {
        background-color: rgba(var(--bs-danger-rgb), 0.15);
        color: var(--bs-danger);
    }

    .action-btn {
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.875rem;
    }

    .search-box {
        position: relative;
    }

    .search-box .form-control {
        border-radius: 1.5rem;
        padding-left: 2.5rem;
    }

    .search-box .bi {
        position: absolute;
        left: 1rem;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        z-index: 10;
    }

    /* 动画效果 */
    .fade-in {
        animation: fadeIn 0.3s ease-in;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">XTEDU管理系统 - 学生管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
        </div>
    </div>
</div>

<!-- 操作卡片 -->
<div class="card fade-in">
    <div class="card-body">
        <form action="<c:url value="/stumanage/studentSearch"/>" method="get" class="mb-0" id="searchForm">
            <div class="row g-3 align-items-end">
                <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                    <label class="form-label">搜索条件</label>
                    <input type="text" name="idCard" class="form-control" id="idCard++"
                           value="${param.idCard}" placeholder="身份证号/手机号/姓名">
                </div>

                <div class="col-xl-1 col-lg-2 col-md-3 col-sm-4">
                    <label class="form-label">性别</label>
                    <select name="gender" class="form-select" id="gender++">
                        <option value="">全部</option>
                        <option value="1" ${param.gender == '1' ? 'selected' : ''}>男</option>
                        <option value="0" ${param.gender == '0' ? 'selected' : ''}>女</option>
                    </select>
                </div>

                <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                    <label class="form-label">班级</label>
                    <select name="classID" class="form-select" id="classID++">
                        <option value="">全部</option>
                        <c:forEach items="${classes}" var="clazz">
                            <option value="${clazz.id}" ${param.classID == clazz.id ? 'selected' : ''}>${clazz.name}</option>
                        </c:forEach>
                    </select>
                </div>

                <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                    <label class="form-label">教育背景</label>
                    <select name="eduBackground" class="form-select" id="eduBackground++">
                        <option value="">全部</option>
                        <option value="高中" ${param.eduBackground == '初中' ? 'selected' : ''}>初中</option>
                        <option value="专科" ${param.eduBackground == '高中' ? 'selected' : ''}>高中</option>
                        <option value="专科" ${param.eduBackground == '专科' ? 'selected' : ''}>专科</option>
                        <option value="本科" ${param.eduBackground == '本科' ? 'selected' : ''}>本科</option>
                        <option value="硕士" ${param.eduBackground == '硕士' ? 'selected' : ''}>硕士</option>
                        <option value="博士" ${param.eduBackground == '博士' ? 'selected' : ''}>博士</option>
                    </select>
                </div>

                <div class="col-xl-5 col-lg-6 col-md-8 col-sm-12">
                    <div class="d-flex gap-2 flex-wrap">
                        <button type="submit" class="btn btn-primary">查询</button>
                        <div class="btn btn-secondary resetSearchForm" id="resetBtn"
                             onclick="resetForm()">重置
                        </div>
                        <div class="btn btn-primary btn-add" data-bs-toggle="modal" data-bs-target="#addStudentModal">
                            <i class="bi bi-plus-circle me-1"></i>添加学生
                        </div>
                        <div class="btn btn-success" onclick="openBatchAddModal()">
                            <i class="bi bi-upload me-1"></i>批量添加
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 数据表格 -->
<div class="table-container fade-in">
    <div class="table-responsive">
        <table class="table table-hover" id="menuTable">
            <thead>
            <tr>
                <th scope="col">学生ID</th>
                <th scope="col">身份证</th>
                <th scope="col">学生姓名</th>
                <th scope="col">性别</th>
                <th scope="col">创建时间</th>
                <th scope="col">班级ID</th>
                <th scope="col">年龄</th>
                <th scope="col">教育背景</th>
                <th scope="col">手机号</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <tbody>
            <c:choose>
                <c:when test="${not empty menuItems}">
                    <c:forEach var="item" items="${menuItems}">
                        <tr>
                            <td>${item.id}</td>
                            <td>${item.idCard}</td>
                            <td>${item.name}</td>
                            <td>${item.gender ? "男" : "女"}</td>
                            <td>${item.createDate}</td>
                                <%--当item.classID等于classes.id的时候，展示classes.name--%>
                            <td>
                                <c:forEach var="classes" items="${classes}">
                                    <c:if test="${item.classID == classes.id}">
                                        ${classes.name}
                                    </c:if>
                                </c:forEach>
                            </td>
                            <td>${item.age}</td>
                            <td>${item.eduBackground}</td>
                            <td>${item.phone}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary action-btn"
                                        onclick="editMenuItem(${item.id})">
                                    <i class="bi bi-pencil me-1"></i>编辑
                                </button>
                                <button class="btn btn-sm btn-outline-danger action-btn"
                                        onclick="deleteMenuItem(${item.id}, '${item.name}')">
                                    <i class="bi bi-trash me-1"></i>删除
                                </button>
                            </td>
                        </tr>
                    </c:forEach>
                </c:when>
                <c:otherwise>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            <i class="bi bi-inbox display-4 d-block mb-2"></i>
                            暂无数据
                        </td>
                    </tr>
                </c:otherwise>
            </c:choose>
            </tbody>
        </table>
    </div>
</div>
<!-- 在表格后面添加分页控件 -->
<c:if test="${not empty menuItems && menuItems.size() > 0}">
    <nav aria-label="Menu navigation">
        <ul class="pagination justify-content-center mt-4" id="menuPagination">
            <li style="flex-basis: 100%; height: 0;"></li>
            <!-- 这里需要添加分页按钮 -->
        </ul>

    </nav>
</c:if>
<%-- 弹出窗口自动消失--%>
<div class="modal fade" id="autoCloseModal" data-bs-autohide="true" data-bs-delay="3000" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                此弹框将在3秒后自动关闭
            </div>
        </div>
    </div>
</div>

<!-- 添加学生模态框 -->
<div class="modal fade" id="addStudentModal" tabindex="-1" aria-labelledby="addStudentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addStudentModalLabel">添加学生信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="studentForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="idCard" class="form-label required">身份证号</label>
                            <input type="text" class="form-control" id="idCard" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="name" class="form-label required">姓名</label>
                            <input type="text" class="form-control" id="name" required>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="gender" class="form-label required">性别</label>
                            <select class="form-select" id="gender" required>
                                <option value="">请选择</option>
                                <option value="true">男</option>
                                <option value="false">女</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="classID" class="form-label required">班级</label>
                            <select class="form-select" id="classID" name="classID" required>
                                <option value="">请选择</option>
                                <%-- 遍历所有班级并生成选项 --%>
                                <c:forEach var="cls" items="${classes}">
                                    <option value="${cls.id}"
                                            <c:if test="${item.classID == cls.id}">selected</c:if>>
                                            ${cls.name}
                                    </option>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="age" class="form-label required">年龄</label>
                            <input type="number" class="form-control" id="age" min="15" max="60" required>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="eduBackground" class="form-label required">学历</label>
                            <select class="form-select" id="eduBackground" required>
                                <option value="">请选择</option>
                                <option value="初中">初中</option>
                                <option value="高中">高中</option>
                                <option value="专科">专科</option>
                                <option value="本科">本科</option>
                                <option value="硕士">硕士</option>
                                <option value="博士">博士</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="phone" class="form-label required">手机号</label>
                            <input type="tel" class="form-control" id="phone" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="addMenuItem()">添加学生</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</div>

<!-- 编辑学生模态框 -->
<div class="modal fade" id="editStudentModal" tabindex="-1" aria-labelledby="editStudentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editStudentModalLabel">编辑学生信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editStudentForm">
                    <!-- 隐藏域存储学生ID -->
                    <input type="hidden" id="edit_id">

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit_idCard" class="form-label required">身份证号</label>
                            <input type="text" class="form-control" id="edit_idCard" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="edit_name" class="form-label required">姓名</label>
                            <input type="text" class="form-control" id="edit_name" required>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="edit_gender" class="form-label required">性别</label>
                            <select class="form-select" id="edit_gender" required>
                                <option value="">请选择</option>
                                <option value="true">男</option>
                                <option value="false">女</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="edit_classID" class="form-label required">班级</label>
                            <select class="form-select" id="edit_classID" required>
                                <option value="">请选择</option>
                                <%-- 遍历所有班级并生成选项 --%>
                                <c:forEach var="cls" items="${classes}">
                                    <option value="${cls.id}">${cls.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="edit_age" class="form-label required">年龄</label>
                            <input type="number" class="form-control" id="edit_age" min="15" max="60" required>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="edit_eduBackground" class="form-label required">学历</label>
                            <select class="form-select" id="edit_eduBackground" required>
                                <option value="">请选择</option>
                                <option value="初中">初中</option>
                                <option value="高中">高中</option>
                                <option value="专科">专科</option>
                                <option value="本科">本科</option>
                                <option value="硕士">硕士</option>
                                <option value="博士">博士</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="edit_phone" class="form-label required">手机号</label>
                            <input type="tel" class="form-control" id="edit_phone" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="updateMenuItem()">更新学生</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 批量添加学生模态框 -->
<div class="modal fade" id="batchAddStudentModal" tabindex="-1" aria-labelledby="batchAddStudentModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="batchAddStudentModalLabel">批量添加学生</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="batchUploadForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="studentFile" class="form-label">选择Excel文件</label>
                        <input class="form-control" type="file" id="studentFile" accept=".xlsx,.xls,.csv" required>
                        <div class="form-text">支持Excel(.xlsx, .xls)或CSV文件格式</div>
                    </div>

                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hasHeader" checked>
                            <label class="form-check-label" for="hasHeader">
                                文件包含表头
                            </label>
                        </div>
                    </div>

                    <div class="alert alert-info">
                        <h6>文件格式要求：</h6>
                        <ul class="mb-0">
                            <li>列顺序：身份证号, 姓名, 性别(男/女), 班级ID, 年龄, 学历, 手机号</li>
                            <li>性别填写：男 或 女</li>
                            <li>学历填写：初中/高中/专科/本科/硕士/博士</li>
                        </ul>
                    </div>

                    <!-- 下载模板按钮 -->
                    <div class="text-center">
                        <button type="button" class="btn btn-outline-primary" onclick="downloadTemplate()">
                            <i class="bi bi-download"></i> 下载模板
                        </button>
                    </div>
                </form>

                <!-- 上传进度显示 -->
                <div id="uploadProgress" class="mt-3" style="display: none;">
                    <div class="progress">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div class="text-center mt-2">
                        <span id="progressText">处理中...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="uploadStudentFile()">开始上传</button>
            </div>
        </div>
    </div>
</div>
<script>
    // 更新菜单状态
    function updateMenuItemState(id, state, element) {
        // 使用URLSearchParams
        const params = new URLSearchParams();// 创建一个URLSearchParams对象
        params.append('id', id);//
        params.append('action', 'update');
        params.append('state', state);
        console.log("发送更新数据：" + params.toString());
        fetch('stumanage', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString()
        })
            .then(response => response.json())
            .catch(error => {
                console.error('Error:', error);
                showError('更新状态时发生错误');
            });
    }

    // 删除菜单 - 使用SweetAlert2美化提示
    function deleteMenuItem(id, name) {
        // 使用SweetAlert2替代原生confirm
        Swal.fire({
            title: '确认删除',
            html: '您确定要删除菜单 <strong>' + name + '</strong> 吗？<br>此操作不可恢复。',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            customClass: {
                popup: 'animated fadeIn'
            },
            backdrop: 'rgba(0,0,0,0.4)',
            showClass: {
                popup: 'animate__animated animate__fadeInDown'
            },
            hideClass: {
                popup: 'animate__animated animate__fadeOutUp'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // 用户确认删除
                showLoading('正在删除中...');

                const params = new URLSearchParams();
                params.append('id', id);
                params.append('action', 'delete');

                fetch('stumanage', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: params.toString()
                })
                    .then(response => response.json())
                    .then(data => {
                        Swal.close(); // 关闭加载提示

                        if (data.success) {
                            // 显示成功提示
                            showSuccess('删除成功').then(() => {
                                location.reload(); // 重新加载页面
                            });
                        } else {
                            showError('删除失败: ' + (data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        Swal.close(); // 关闭加载提示
                        console.error('Error:', error);
                        showError('删除时发生错误: ' + error.message);
                    });
            }
        });
    }

    // 显示加载中的提示
    function showLoading(message) {
        return Swal.fire({
            title: '请稍候',
            html: message,
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
    }

    // 显示成功提示
    function showSuccess(message) {
        return Swal.fire({
            title: '成功',
            text: message,
            icon: 'success',
            confirmButtonColor: '#3085d6',
            confirmButtonText: '2秒后自动关闭',
            timer: 2000, // 2秒后自动关闭
            customClass: {
                popup: 'animated fadeIn'
            }
        });
    }

    // 显示错误提示
    function showError(message) {
        return Swal.fire({
            title: '错误',
            html: message,
            icon: 'error',
            confirmButtonColor: '#d33',
            confirmButtonText: '2秒后自动关闭',
            timer: 2000,// 2秒后自动关闭
            customClass: {
                popup: 'animated fadeIn'
            }
        });
    }
</script>
<%--分页功能实现--%>
<script>
    $(document).ready(function () {
        // 分页功能实现
        const itemsPerPage = 8;
        const $rows = $('#menuTable tbody tr').not(':has(td[colspan])'); // 排除"暂无数据"行
        const totalItems = $rows.length;

        if (totalItems <= itemsPerPage) {
            return; // 数据不足一页，不需要分页
        }

        const totalPages = Math.ceil(totalItems / itemsPerPage);
        let currentPage = 1;

        // 初始化分页
        initPagination();
        showPage(1);

        function initPagination() {
            const $pagination = $('#menuPagination');
            $pagination
                .empty();

            // 添加页码信息
            // $pagination
            //     .append(
            //         '<li class="page-item disabled">' +
            //         '<span class="page-link">共 ' + totalItems + ' 条记录</span>' +
            //         '</li>'
            //     );

            // 添加上一页按钮
            $pagination
                .append(
                    '<li class="page-item" id="prevPage">' +
                    '<a class="page-link" href="javascript:void(0)" aria-label="Previous">' +
                    '<span aria-hidden="true">&laquo;</span>' +
                    '</a>' +
                    '</li>'
                );

            // 添加页码按钮
            for (let i = 1; i <= totalPages; i++) {
                $pagination
                    .append(
                        '<li class="page-item page-number' + (i === 1 ? ' active' : '') + '">' +
                        '<a class="page-link" href="javascript:void(0)" data-page="' + i + '">' + i + '</a>' +
                        '</li>'
                    );
            }

            // 添加下一页按钮
            $pagination
                .append(
                    '<li class="page-item" id="nextPage">' +
                    '<a class="page-link" href="javascript:void(0)" aria-label="Next">' +
                    '<span aria-hidden="true">&raquo;</span>' +
                    '</a>' +
                    '</li>'
                );

            // 绑定事件
            $('#prevPage').click(function () {
                if (currentPage > 1) {
                    showPage(currentPage - 1);
                }
            });

            $('#nextPage').click(function () {
                if (currentPage < totalPages) {
                    showPage(currentPage + 1);
                }
            });

            $('.page-number a').click(function () {
                const page = parseInt($(this).data('page'));
                showPage(page);
            });
        }

        function showPage(page) {
            currentPage
                = page;

            // 隐藏所有行
            $rows
                .hide();

            // 显示当前页的行
            const startIndex = (page - 1) * itemsPerPage;
            const endIndex = Math.min(startIndex + itemsPerPage, totalItems);

            for (let i = startIndex; i < endIndex; i++) {
                $($rows[i]).show();
            }

            // 更新分页状态
            updatePaginationState();
        }

        function updatePaginationState() {
            // 更新页码按钮状态
            $('.page-number').removeClass('active');
            $(`.page-number:has(a[data-page="${currentPage}"])`).addClass('active');

            // 更新上一页/下一页按钮状态
            $('#prevPage').toggleClass('disabled', currentPage === 1);
            $('#nextPage').toggleClass('disabled', currentPage === totalPages);
        }
    });
</script>

<%--添加学生的模态框,添加功能操作--%>
<script>
    // 在页面加载完成后，为表单绑定提交事件
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('studentForm');

        if (form) {
            form.addEventListener('submit', function (event) {
                // 1. 阻止表单的默认提交行为（页面刷新）
                event.preventDefault();

                // 2. 调用添加学生的函数
                addMenuItem();
            });
        }
    });
    <%--点击重置按钮重置搜索条件--%>

    function resetForm() {
        document.getElementById("resetBtn").addEventListener("click", function (event) {

            document.getElementById("searchForm").reset();
            window.location.reload();

        })
    }

    //addMenuItem 函数基本保持不变，但不再需要 event 参数
    function addMenuItem() {
        // 获取表单数据 (代码不变)
        const idCard = document.getElementById('idCard').value.trim();
        const name = document.getElementById('name').value.trim();
        const gender = document.getElementById('gender').value;
        const classID = document.getElementById('classID').value;
        const age = document.getElementById('age').value;
        const eduBackground = document.getElementById('eduBackground').value;
        const phone = document.getElementById('phone').value.trim();

        // 表单验证 (代码不变)
        if (!idCard || !name || !gender || !classID || !age || !eduBackground || !phone) {
            alert('请填写所有必填字段！');
            return; // 验证失败，直接返回
        }

        // 创建并发送数据 (代码不变)
        const formData = new URLSearchParams();
        formData.append('idCard', idCard);
        formData.append('name', name);
        formData.append('gender', gender);
        formData.append('classID', classID);
        formData.append('age', age);
        formData.append('eduBackground', eduBackground);
        formData.append('phone', phone);

        fetch('stumanage/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: formData.toString()
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess('学生信息添加成功！');
                    // 关闭模态框并刷新列表
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addStudentModal'));
                    modal.hide();
                    location.reload(); // 重新加载页面
                } else {
                    console.log(formData);
                    console.log(data)
                    showError('添加失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('添加学生信息失败:', error);
                showError('添加学生信息失败，请重试！');
            });
    }

    // 编辑菜单 - 打开模态框并反写数据
    function editMenuItem(id) {
        // 首先获取学生数据
        const studentId = id;
        fetch(`stumanage/update?id=` + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(student => {
                if (student) {
                    // 反写数据到编辑模态框
                    document.getElementById('edit_id').value = student.id;
                    document.getElementById('edit_idCard').value = student.idCard;
                    document.getElementById('edit_name').value = student.name;
                    document.getElementById('edit_gender').value = student.gender.toString();
                    document.getElementById('edit_classID').value = student.classID;
                    document.getElementById('edit_age').value = student.age;
                    document.getElementById('edit_eduBackground').value = student.eduBackground;
                    document.getElementById('edit_phone').value = student.phone;

                    // 显示编辑模态框
                    const editModal = new bootstrap.Modal(document.getElementById('editStudentModal'));
                    editModal.show();
                } else {
                    showError('获取学生信息失败！');
                }
            })
            .catch(error => {
                console.error('获取学生信息失败:', error);
                showError('获取学生信息失败，请重试！');
            });
    }

    // 更新学生信息
    function updateMenuItem() {
        // 获取表单数据
        const id = document.getElementById('edit_id').value;
        const idCard = document.getElementById('edit_idCard').value.trim();
        const name = document.getElementById('edit_name').value.trim();
        const gender = document.getElementById('edit_gender').value;
        const classID = document.getElementById('edit_classID').value;
        const age = document.getElementById('edit_age').value;
        const eduBackground = document.getElementById('edit_eduBackground').value;
        const phone = document.getElementById('edit_phone').value.trim();

        // 表单验证
        if (!id || !idCard || !name || !gender || !classID || !age || !eduBackground || !phone) {
            showError('请填写所有必填字段！');
            return;
        }

        // 创建并发送数据
        const formData = new URLSearchParams();
        formData.append('id', id);
        formData.append('idCard', idCard);
        formData.append('name', name);
        formData.append('gender', gender);
        formData.append('classID', classID);
        formData.append('age', age);
        formData.append('eduBackground', eduBackground);
        formData.append('phone', phone);

        fetch('stumanage/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: formData.toString()
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showSuccess('学生信息更新成功！');
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editStudentModal'));
                    modal.hide();
                    // 刷新页面或表格数据
                    location.reload(); // 或者调用您的刷新函数
                } else {
                    showError('更新失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('更新学生信息失败:', error);
                showError('更新学生信息失败，请重试！');
            });
    }
</script>

<%--批量添加学生信息--%>
<script>
    // 下载模板
    function downloadTemplate() {
        // 创建一个示例数据链接
        const templateData = [
            ['身份证号', '姓名', '性别', '班级ID', '年龄', '学历', '手机号'],
            ['110101199001011234', '张三', '男', '1', '20', '本科', '13800138000'],
            ['110101199002021235', '李四', '女', '2', '21', '硕士', '13900139000']
        ];

        // 将数据转换为CSV格式
        const csvContent = templateData.map(row => row.join(',')).join('\n');
        const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);

        link.setAttribute('href', url);
        link.setAttribute('download', '学生信息模板.csv');
        link.style.visibility = 'hidden';

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // 上传文件
    function uploadStudentFile() {
        const fileInput = document.getElementById('studentFile');
        const hasHeader = document.getElementById('hasHeader').checked;
        const progressDiv = document.getElementById('uploadProgress');
        const progressBar = progressDiv.querySelector('.progress-bar');
        const progressText = document.getElementById('progressText');

        if (!fileInput.files || fileInput.files.length === 0) {
            alert('请选择要上传的文件');
            return;
        }

        const file = fileInput.files[0];
        const formData = new FormData();
        formData.append('file', file);
        formData.append('hasHeader', hasHeader.toString());

        // 显示进度条
        progressDiv.style.display = 'block';
        progressBar.style.width = '0%';
        progressText.textContent = '开始上传...';

        fetch('stumanage/batchAdd', {
            method: 'POST',
            body: formData
            // 注意：使用FormData时不要设置Content-Type头，浏览器会自动设置
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('上传失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    progressBar.style.width = '100%';
                    progressBar.classList.add('bg-success');
                    progressText.innerHTML = `
                <strong>上传成功！</strong><br>
                成功:` + data.successCount + `条,
                失败: ` + data.failCount + ` 条
                ${data.failCount > 0 ? '<br><small>失败详情请查看控制台</small>' : ''}`;

                    // 3秒后关闭模态框并刷新页面
                    setTimeout(() => {
                        const modal = bootstrap.Modal.getInstance(document.getElementById('batchAddStudentModal'));
                        modal.hide();
                        location.reload();
                    }, 3000);
                } else {
                    throw new Error(data.message || '上传失败');
                }
            })
            .catch(error => {
                console.error('上传失败:', error);
                progressBar.classList.add('bg-danger');
                progressText.innerHTML = `<strong>上传失败：</strong>${error.message}`;
            });
    }

    // 添加打开模态框的函数
    function openBatchAddModal() {
        // 重置表单
        document.getElementById('batchUploadForm').reset();
        document.getElementById('uploadProgress').style.display = 'none';

        const modal = new bootstrap.Modal(document.getElementById('batchAddStudentModal'));
        modal.show();
    }
</script>
<jsp:include page="footer.jsp"/>